using System;
using System.Linq;
using System.Data;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using Widgetsphere.Core.DataAccess;
using Widgetsphere.Core.Util;
using Widgetsphere.Core.Logging;
using Widgetsphere.Core.Exceptions;
using Acme.AuditExample;
using Acme.AuditExample.Business;
using Acme.AuditExample.Business.Objects;
using Acme.AuditExample.Business.Rules;
using Acme.AuditExample.Business.SelectCommands;
using System.IO;
using System.Data.SqlClient;

namespace Acme.AuditExample.Domain.Objects
{
	#region internal class
	/// <summary>
	/// This is an customizable extender for the domain class associated with the 'Customer' object collection
	/// </summary>
	[Serializable()]
	[System.ComponentModel.DesignerCategoryAttribute("code")]
	partial class DomainCustomerCollection : PersistableDomainCollectionBase, IEnumerable, ISerializable, IDisposable
	{
		#region Member Variables

		//Generated Relationships This Object Plays Parent Role


		#endregion

		#region ISerializable Members
		/// <summary>
		/// Serialization constructor
		/// </summary>
		protected DomainCustomerCollection(SerializationInfo info, StreamingContext context):this()
		{

		}

		/// <summary>
		/// Method used internally for serialization
		/// </summary>
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{

		}
		#endregion

		#region Properties

		internal SubDomain SubDomain
		{
			get{ return (SubDomain)this.DataSet; }
		}

		internal string Modifier
		{
			get{ return SubDomain.Modifier; }
			set { SubDomain.Modifier = value; }
		}

		#endregion

		#region Contructors /Initialization

		internal DomainCustomerCollection()
		{
			try
			{
				base.TableName = "CustomerCollection";
				this.InitClass();
			}
			catch (System.Data.DBConcurrencyException dbcex) { throw new ConcurrencyException(GlobalValues.ERROR_CONCURRENCY_FAILURE, dbcex); }
			catch (System.Data.SqlClient.SqlException sqlexp) { if (sqlexp.Number == 547 || sqlexp.Number == 2627) throw new UniqueConstraintViolatedException(GlobalValues.ERROR_CONSTRAINT_FAILURE, sqlexp); else throw; }
			catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); throw; }
		}

		private void InitClass() 
		{
			BeginInit();
			this.CustomerIdColumn = new DataColumn("CustomerId", typeof(System.Guid), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CustomerIdColumn);
			this.CustomerIdColumn.AllowDBNull = false;
			this.CustomerIdColumn.DefaultValue = System.Guid.Empty;
			this.CustomerIdColumn.Caption = "";
			this.NameColumn = new DataColumn("Name", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.NameColumn);
			this.NameColumn.Caption = "";
			this.ModifiedbyColumn = new DataColumn("Modifiedby", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.ModifiedbyColumn);
			this.ModifieddateColumn = new DataColumn("Modifieddate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.ModifieddateColumn);
			this.CreatedbyColumn = new DataColumn("Createdby", typeof(string), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CreatedbyColumn);
			this.CreateddateColumn = new DataColumn("Createddate", typeof(DateTime), null, System.Data.MappingType.Element);
			base.Columns.Add(this.CreateddateColumn);
			this.TimestampColumn = new DataColumn("Timestamp", typeof(System.Byte[]), null, System.Data.MappingType.Element);
			base.Columns.Add(this.TimestampColumn);
			base.Constraints.Add(new UniqueConstraint("PrimaryKey", new DataColumn[] {this.CustomerIdColumn}, true));
			EndInit();
		}

		private bool mModifyUpdateOn = true;

		/// <summary>
		/// Raises the RowChanged event.
		/// </summary>
		protected override void OnRowChanged(DataRowChangeEventArgs e)
		{
			base.OnRowChanged(e);
			if(e.Action == DataRowAction.Change && mModifyUpdateOn)
			{
				mModifyUpdateOn = false;
				if ((e.Row[this.ModifiedbyColumn] == System.DBNull.Value) || ((string)e.Row[this.ModifiedbyColumn] != this.Modifier)) e.Row[this.ModifiedbyColumn] = this.Modifier;
				mModifyUpdateOn = true;
			}
		}

		#endregion

		#region Database Retrieval

		internal DomainCustomer NewItem()
		{
			return this.NewItem(Guid.NewGuid());
		}

		internal DomainCustomer NewItem(System.Guid key)
		{
			DomainCustomer retval = (DomainCustomer)(base.NewRow());
			((DataRow)retval)[CustomerIdColumn] = key;
			return retval;
		}


		internal void AddItem(DomainCustomer item)
		{
			base.Rows.Add(item);
		}

		internal void InsertAtCustomer(DomainCustomer item, int pos)
		{
			base.Rows.InsertAt(item, pos);
		}

		internal virtual void Persist()
		{
			this.SubDomain.Persist();
		}

		#region Select Methods

		internal static DomainCustomerCollection RunSelect(string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new CustomerSelectAll());
			sd.RunSelectCommands();
			return (DomainCustomerCollection)sd.GetDomainCollection(Collections.CustomerCollection);
		}

		internal static DomainCustomerCollection SelectByCustomerPks(List<CustomerPrimaryKey> primaryKeys, string modifier)
		{
			SubDomain sd = new SubDomain(modifier);
			sd.AddSelectCommand(new CustomerSelectByPks(primaryKeys));
			sd.RunSelectCommands();
			return (DomainCustomerCollection)sd.GetDomainCollection(Collections.CustomerCollection);
		}

		#endregion

		#endregion

		#region DomainCustomer Collection Methods
		internal void RemoveCustomer(DomainCustomer item) 
		{
			base.Rows.Remove(item);
		}

		internal virtual int Count 
		{
			get { return base.Rows.Count; }
		}

		/// <summary>
		/// Returns an enumerator that can be used to iterate through the collection.
		/// </summary>
		/// <returns>An Enumerator that can iterate through the objects in this collection.</returns>
		public virtual System.Collections.IEnumerator GetEnumerator() 
		{
			return base.Rows.GetEnumerator();
		}

		/// <summary>
		/// Gets or sets the element at the specified index.
		/// </summary>
		/// <param name="index">The zero-based index of the element to get or set. </param>
		/// <returns>The element at the specified index.</returns>
		internal DomainCustomer this[int index] 
		{
			get { return ((DomainCustomer)(base.Rows[index])); }
		}

		internal DomainCustomer GetCustomer(System.Guid customerId)
		{
			return ((DomainCustomer)(base.Rows.Find(new object[] { customerId })));
		}

		#endregion

		#region Data Columns Setup

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn CustomerIdColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting("", false, 0)]
		public DataColumn NameColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifieddateColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn ModifiedbyColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreateddateColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn CreatedbyColumn { get; protected set; }

		[Widgetsphere.Core.Attributes.DataSetting(false)]
		public DataColumn TimestampColumn { get; protected set; }

		#endregion

		#region Protected Overrides

		/// <summary>
		/// Create a new instance of this object type
		/// </summary>
		protected override DataTable CreateInstance()
		{
			return new DomainCustomerCollection();
		}

		/// <summary>
		/// Create new row from a DataRowBuilder
		/// </summary>
		/// <param name="builder">The DataRowBuilder object that is used to create the new row</param>
		/// <returns>A new datarow of type 'Customer'</returns>
		protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
		{
			DomainCustomer retval = new DomainCustomer(builder);
			return retval;
		}

		/// <summary>
		/// Returns the type of the datarow that this collection holds
		/// </summary>
		protected override System.Type GetRowType() 
		{
			return typeof(DomainCustomer);
		}
		#endregion

		#region Implement Persistable Table Abstact Methods

		/// <summary>
		/// Gets a list of parameters for SQL update commands.
		/// </summary>
		protected override List<IDbDataParameter> GetUpdateFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL insert commands.
		/// </summary>
		protected override List<IDbDataParameter> GetInsertFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Gets a list of parameters for SQL delete commands.
		/// </summary>
		protected override List<IDbDataParameter> GetDeleteFreeSqlParameters()
		{
			return null;
		}

		/// <summary>
		/// Determines if the stored procedure or SQL text is used for CRUD operations.
		/// </summary>
		protected override bool UseStoredProcedure
		{
			get { return true; }
		}

		/// <summary>
		/// The stored procedure name that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerDelete]"; }
		}

		/// <summary>
		/// The SQL that performs deletes for the objects in this collection
		/// </summary>
		protected override string DeleteSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerInsert]"; }
		}

		/// <summary>
		/// The SQL that performs inserts for the objects in this collection
		/// </summary>
		protected override string InsertSQLText
		{
			get { return null; }
		}

		/// <summary>
		/// The stored procedure name that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateStoredProcedureName
		{
			get { return "[dbo].[gen_CustomerUpdate]"; }
		}

		/// <summary>
		/// The SQL that performs updates for the objects in this collection
		/// </summary>
		protected override string UpdateSQLText
		{
			get { return null; }
		}

		public override void SetChildSelectedFalse()
		{
		}

		/// <summary>
		/// Creates the referential integrity for this collection
		/// </summary>
		public override void CreateRelations()
		{
		}

		bool _handlingError = false;
		/// <summary>
		/// Determines if errors are handled by this object
		/// </summary>
		public override bool HandleErrors()
		{
			if (_handlingError) return false;
			_handlingError = true;
			try
			{
			return false;
			}
			catch
			{
				throw;
			}
			finally
			{
				_handlingError = false;
			}
		}
		#endregion 

		#region Helper Methods

		internal virtual string GetPrimaryKeyXml()
		{
			return GetPrimaryKeyXml(((IEnumerable<Acme.AuditExample.Business.Objects.Customer>)new Acme.AuditExample.Business.Objects.CustomerCollection(this)).Select(x => x.PrimaryKey));
		}

		internal static string GetPrimaryKeyXml(Acme.AuditExample.Business.Objects.CustomerPrimaryKey primaryKey)
		{
			List<Acme.AuditExample.Business.Objects.CustomerPrimaryKey> list = new List<Acme.AuditExample.Business.Objects.CustomerPrimaryKey>();
			list.Add(primaryKey);
			return GetPrimaryKeyXml(new List<Acme.AuditExample.Business.Objects.CustomerPrimaryKey>(list));
		}

		internal static string GetPrimaryKeyXml(IEnumerable<Acme.AuditExample.Business.Objects.CustomerPrimaryKey> primaryList)
		{
			StringWriter sWriter = new StringWriter();
			XmlTextWriter xWriter = new XmlTextWriter(sWriter);
			xWriter.WriteStartDocument();
			xWriter.WriteStartElement("ItemList");
			foreach(Acme.AuditExample.Business.Objects.CustomerPrimaryKey primaryKey in primaryList)
			{
				xWriter.WriteStartElement("Item");
				xWriter.WriteStartElement("CustomerId");
				xWriter.WriteString(primaryKey.CustomerId.ToString());
				xWriter.WriteEndElement();
				xWriter.WriteEndElement();
			}
			xWriter.WriteEndElement();
			xWriter.WriteEndDocument();
			xWriter.Flush();
			xWriter.Close();
			return sWriter.ToString();
		}

		#endregion

		#region Methods

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
		}

		#endregion

	}
	#endregion

}
